package com.dao.impl;

import com.dao.FunctionDAO;
import com.dao.UserDAO;
import com.entity.Function;
import com.entity.UserInfo;
import com.sys.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限管理的数据访问类
 * 
 * @author xieqing
 * 
 */
public class FunctionDaoImpl implements FunctionDAO {

	public boolean add(Function function) {
		String sql = "insert  into function(url,name,mark ) "
				+ "" + " values(?,?,?)";
		List<Object> list = new ArrayList<Object>();
		list.add(function.getUrl());
		list.add(function.getName());
		list.add(function.getMark());
		return DBUtils.saveOrUpdate(sql, list.toArray());
	}

	public boolean update(Function function) {
		String sql = "update function  set name=?,url=? ,mark=?  where id=?";
		List<Object> list = new ArrayList<Object>();
		list.add(function.getName());
		list.add(function.getUrl());
		list.add(function.getMark());
		list.add(function.getId());

		return DBUtils.saveOrUpdate(sql, list.toArray());
	}

	/**
	 * 查询 权限
	 * 
	 * @param
	 *
	 * @return
	 */
	public List<Function> getList(String sql, Object[] params) {
		Connection con = null;
		PreparedStatement pre = null;
		ResultSet res = null;

		try {
			con = DBUtils.getConnection();
			pre = con.prepareStatement(sql);
			if (params != null && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					pre.setObject(i + 1, params[i]);
				}
			}

			res = pre.executeQuery();
			List<Function> list = new ArrayList<Function>();
			while (res.next()) {
				Function function = new Function();

				function.setId(res.getInt("id"));
				function.setName(res.getString("name"));
				function.setUrl(res.getString("url"));
				function.setMark(res.getInt("mark"));

				list.add(function);
			}

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(con, pre, res);
		}

		return null;
	}

	public List<Map> getCount() {

		Connection con = null;
		PreparedStatement pre = null;
		ResultSet res = null;

		try {
			String sql = "SELECT b.role_name,COUNT(b.role_name) total FROM user_info a,role_info b"
					+ " WHERE a.role_id = b.role_id AND a.user_mark='1' AND b.role_mark='1'"
					+ "  GROUP BY b.role_name";
			con = DBUtils.getConnection();
			pre = con.prepareStatement(sql);
			res = pre.executeQuery();
			List<Map> list = new ArrayList<Map>();
			while (res.next()) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("role_name", res.getObject("role_name"));
				map.put("total", res.getObject("total"));

				list.add(map);
			}

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(con, pre, res);
		}
		
		return null;
	}
}
